export default {
  data() {
    return {
      vfEvents: {}
    }
  },

  methods: {
    emit$(eventName, data) {
      if (this.vfEvents[eventName]) {
        this.vfEvents[eventName].forEach((fn) => {
          fn(data)
        })
      }
    },

    on$(eventName, fn) {
      this.vfEvents[eventName] = this.vfEvents[eventName] || []
      this.vfEvents[eventName].push(fn)
    },

    off$(eventName, fn) {
      if (this.vfEvents[eventName]) {
        if (fn === undefined || fn === null) {
          this.vfEvents[eventName].length = 0
          return
        }

        for (let i = 0; i < this.vfEvents[eventName].length; i++) {
          if (this.vfEvents[eventName][i] === fn) {
            this.vfEvents[eventName].splice(i, 1)
            break
          }
        }
      }
    },

    dispatch: function dispatch(componentName, eventName, params) {
      console.log('===============================================')
      let parent = this.$parent || this.$root

      let name = parent.$options.componentName

      while (parent && (!name || name !== componentName)) {
        parent = parent.$parent
        // console.log('aa', componentName, name, parent)
        if (parent) {
          name = parent.$options.componentName
        }
        console.log('aa', componentName, name, parent)
        // console.log('name=', name)
      }
      if (parent) {
        if (parent.emit$) {
          parent.emit$.call(parent, eventName, params)
        }
      }
    }
  }
}
